package main

import (
	"context"
	"flag"
	"fmt"

	"gozero-microservices/order-service/rpc/internal/config"
	"gozero-microservices/order-service/rpc/internal/interceptor"
	ordersrvServer "gozero-microservices/order-service/rpc/internal/server/ordersrv"
	"gozero-microservices/order-service/rpc/internal/svc"
	"gozero-microservices/order-service/rpc/types/order"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/core/trace"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

var configFile = flag.String("f", "etc/order.yaml", "the config file")

func main() {
	var env string
	// 运行环境
	flag.StringVar(&env, "env", "dev", "运行环境")
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	// 启用追踪代理
	trace.StartAgent(c.Telemetry)

	// 设置环境变量
	c.Env = env

	ctx := svc.NewServiceContext(c)

	// 输出当前环境
	logx.Info(context.Background(), " current environment: "+env)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		order.RegisterOrderSrvServer(grpcServer, ordersrvServer.NewOrderSrvServer(ctx))

		// 获取dtm grpc服务地址，貌似不行需要在gateway-api中创建grpc服务
		// dtmGrpcServerUrl := ""
		// switch c.Env {
		// case "dev":
		// 	dtmGrpcServerUrl = c.DtmConf.Dev.GrpcServer
		// case "test":
		// 	dtmGrpcServerUrl = c.DtmConf.Test.GrpcServer
		// case "prod":
		// 	dtmGrpcServerUrl = c.DtmConf.Prod.GrpcServer
		// }

		// Workflow 进行初始化
		// workflow.InitGrpc(dtmGrpcServerUrl, c.ListenOn, grpcServer)

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})
	defer s.Stop()

	// 添加单级限流器拦截器
	switch ctx.Config.LimiterConf.Mode {
	case "period":
		s.AddUnaryInterceptors(interceptor.PeriodLimiterInterceptor(ctx))
	case "token":
		s.AddUnaryInterceptors(interceptor.TokenLimiterInterceptor(ctx))
	}

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
